<template>
  <li v-for="(menuitem, index) in menu" :key="`_root${index}`">
    <button v-if="menuitem.children && root" v-styleclass="{ selector: '@next', enterFromClass: 'hidden', enterActiveClass: 'animate-slidedown', leaveToClass: 'hidden', leaveActiveClass: 'animate-slideup' }" type="button">
            <span class="menu-icon">
                <i :class="menuitem.icon"></i>
            </span>
      <span class="button-text">{{ menuitem.name }}</span>
      <i class="menu-toggle-icon pi pi-angle-down"></i>
    </button>

    <a v-if="menuitem.href" :href="menuitem.href" target="_blank" rel="noopener noreferrer">
            <span v-if="menuitem.icon && root" class="menu-icon">
                <i :class="menuitem.icon"></i>
            </span>
      <span class="button-text">{{ menuitem.name }}</span>
      <Tag v-if="menuitem.badge" :value="menuitem.badge"></Tag>
    </a>

    <router-link  v-if="menuitem.to" :to="menuitem.to" :class="{ 'router-link-active': menuitem.to === $route.fullPath }">
      <span v-if="menuitem.icon && root" class="menu-icon">
                <i :class="menuitem.icon"></i>
            </span>
      <span class="button-text">{{ menuitem.name }}</span>
      <Tag v-if="menuitem.badge" :value="menuitem.badge"></Tag>
    </router-link>

    <span v-if="!root && menuitem.children" class="menu-child-category">{{ menuitem.name }}</span>
    <div v-if="menuitem.children" :class="{ hidden: menuitem.children && root && isActiveRootMenuItem(menuitem) }">
      <ol>
        <MenuItem :root="false" :menu="menuitem.children"></MenuItem>
      </ol>
    </div>
  </li>
</template>

<script lang="ts" setup>

import { useRouter } from 'vue-router'
import type { MenuItem } from '@/types/index/menu.ts'

const router = useRouter()

const props = defineProps({
  root: Boolean,
  menu: Object
})

const isActiveRootMenuItem = (menuitem: MenuItem) => {
  const currentRouteName: string = String(router.currentRoute.value?.name!)
  console.log('currentRouteName', currentRouteName)
  return (
    menuitem.children &&
    !menuitem.children.some((item) => item.to === `/${currentRouteName}` ||
      (item.to && `/${currentRouteName}`.startsWith(item.to)) ||
      (item.children && item.children.some((it) => it.to === `/${currentRouteName}`)) )
  );
}
</script>
<style scoped lang="scss">
.button-text{
  white-space: nowrap;
}
</style>
